import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FORM_ROW_OPTIONS, DATETIME_FORMAT} from '../constants';
import {approvePassData, approveRejectData, getDetail} from './api';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {salePlanAssembleMethod, salePlanOrderResultJudgeResult} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import {injectIntl} from './intl';
import styles from './style.css';
import Return from '../common/Return';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const FormItem = Form.Item;
const today = new Date();

class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                        approveDetails: res.data.approveDetails,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmitPass = () => {
        const data = this.state.data;
        const condition = {
            id: this.props.id,
            approvedContent: data.approvedContent,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        approvePassData([condition]).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitReject = () => {
        const data = this.state.data;
        const condition = {
            id: this.props.id,
            approvedContent: data.approvedContent,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        approveRejectData([condition]).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, approveDetails, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        let total = 0;
        total = details.length;
        let detailTotal = 0;
        if(details)
            details.forEach(d => {
                detailTotal += (d.n1Quantity + d.n2Quantity + d.n3Quantity + d.n4Quantity + d.n5Quantity + d.n6Quantity);
            });
        const columns = [{
            title: formatMessage({
                id: 'approvePanel.column.assembleMethod',
                defaultMessage: '装配方式'
            }),
            dataIndex: 'assembleMethod',
            render: text => conventEnumValueToString(salePlanAssembleMethod, text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.materialGroupKDBOMCode',
                defaultMessage: '物料组号或KDBOM编号'
            }),
            dataIndex: 'materialGroupKDBOMCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.referenceMaterialGroupKDBOMCode',
                defaultMessage: '参考物料组号或KDBOM编号'
            }),
            dataIndex: 'referenceMaterialGroupKDBOMCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.modelCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'modelCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.newModel',
                defaultMessage: '是否新车型'
            }),
            dataIndex: 'newModel',
            render: text => text ? formatMessage({
                id: 'approvePanel.column.y',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'approvePanel.column.n',
                defaultMessage: '否'
            }),
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n1Quantity',
                defaultMessage: 'N+1月订购数量'
            }),
            dataIndex: 'n1Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n2Quantity',
                defaultMessage: 'N+2月订购数量'
            }),
            dataIndex: 'n2Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n3Quantity',
                defaultMessage: 'N+3月订购数量'
            }),
            dataIndex: 'n3Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n4Quantity',
                defaultMessage: 'N+4月订购数量'
            }),
            dataIndex: 'n4Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n5Quantity',
                defaultMessage: 'N+5月订购数量'
            }),
            dataIndex: 'n5Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n6Quantity',
                defaultMessage: 'N+6月订购数量'
            }),
            dataIndex: 'n6Quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.detailRemark',
                defaultMessage: '备注'
            }),
            dataIndex: 'detailRemark',
        }];
        const approveColumns = [{
            title: formatMessage({
                id: 'detailPanel.column.approveSequence',
                defaultMessage: '审核序号'
            }),
            dataIndex: 'approveSequence',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approvedContent',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approvedContent',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(salePlanOrderResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation',
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '滚动计划信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.planCode',
                                        defaultMessage: '计划编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.planCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approvePanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.dealerCode === undefined ? '' : `(${data.dealerCode})${data.dealerName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.marketDepartmentName',
                                        defaultMessage: '大区'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.marketDepartmentName}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.brandCode === undefined ? '' : `(${data.brandCode})${data.brandName}`}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.data.manufacturerId',
                                        defaultMessage: '生产工厂'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.manufacturerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.createTime',
                                        defaultMessage: '提报日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(today, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.submitYear',
                                        defaultMessage: '年份'
                                    })} {...FORM_OPTIONS.item}>
                                        {today.getFullYear()}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.submitMonth',
                                        defaultMessage: '月份'
                                    })} {...FORM_OPTIONS.item}>
                                        {today.getMonth() + 1}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.total',
                                        defaultMessage: '总数量'
                                    })} {...FORM_OPTIONS.item}>
                                        {detailTotal}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.detailTotal',
                                        defaultMessage: '总品种数'
                                    })} {...FORM_OPTIONS.item}>
                                        {total}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approvedContent',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            name="approvedContent"
                                            type="textarea"
                                            value={data.approvedContent}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.detail',
                            defaultMessage: '滚动计划清单'
                        })} extra={<div>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.approveDetails',
                            defaultMessage: '审核清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={approveColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={approveDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            onClick={this.onSubmitReject}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitReject',
                                defaultMessage: '驳回'
                            })}
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.onSubmitPass}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitPass',
                                defaultMessage: '通过'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
